package com.kevms.phonewars;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.opengl.Matrix;

/** 
* @class PWSensorListener
* 
* @brief SensorEventListener used to listen for Sensor Events
* 
* This SensorEventListener handles Sensor Events and updates 
* player objects accordingly.
*/ 
public class PWSensorListener implements SensorEventListener {

	//private static final String TAG = "PWSensorListener";
	private final Combat combat;
	public SensorManager sensorManager;
	
	private float[] R = new float[16];
	private float[] Rinv = new float[16];
	private float[] I = new float[16];
	private float[] mGravs = new float[3];
	private float[] mGeoMags = new float[3];
	private float[] dirObjectSpace = new float[4];
	private float[] dir = new float[4];
	
	public PWSensorListener(Combat combat) {
		this.combat = combat;
		sensorManager = (SensorManager)this.combat.getSystemService(Combat.SENSOR_SERVICE);
	}
	
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
	}

	public synchronized void onSensorChanged(SensorEvent event) {
		if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
			System.arraycopy(event.values, 0, mGeoMags, 0, 3);
		}
		else if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			System.arraycopy(event.values, 0, mGravs, 0, 3);
		}
		
		boolean success = SensorManager.getRotationMatrix(R, I, mGravs, mGeoMags);
		if (success) {
			dirObjectSpace[0] = 0;
			dirObjectSpace[1] = 1;
			dirObjectSpace[2] = 0;
			dirObjectSpace[3] = 1;
			Matrix.transposeM(Rinv, 0, R, 0);
			Matrix.multiplyMV(dir,0,Rinv,0,dirObjectSpace,0);
			
			float invlen = (float)(1.0/Math.sqrt(dir[0] * dir[0] + dir[1] * dir[1]));
			dir[0] = dir[0] * invlen;
			dir[1] = dir[1] * invlen;
			
			String s = "Orientation: " +
			"\n\tX = " + dir[0] +
			"\n\tY = " + dir[1] +
			"\n\tLen = " + Math.sqrt(dir[0] * dir[0] + dir[1] * dir[1]);
			this.combat.tvDump.setText(s);
			
			/*
			this.combat.tvScore.setText("Direction:" +
			"\n\t" + dir[0] +
			"\n\t" + dir[1] +
			"\n\t" + dir[2] +
			"\n\t" + dir[3]);*/
			this.combat.player.setOrientation(dir);
		}
	}
	
	public void start() {
		sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL);
		sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
	}
	
	public void stop() {
		sensorManager.unregisterListener(this.combat.sensorListener);
	}
}